#include"mystdio.h"

void _fwrite(const void* tmp,int num,_FILE* fp)
{
  //write into buffer
  memcpy(fp->buffer+fp->_SIZE,tmp,num);
  fp->_SIZE+=num;
  if(fp->_flags == SYNC_NOW)
  {
    if(fp->_SIZE>0)
    {
      write(fp->fileon,fp->buffer,fp->_SIZE);
      fp->_SIZE = 0;
    }
  }
  else if(fp->_flags == SYNC_FULL)
  {
    if(fp->_SIZE == fp->cap)
    {
      write(fp->fileon,fp->buffer,fp->_SIZE);
      fp->_SIZE = 0;
    }
  }
  else if(fp->_flags == SYNC_LINE)
  {
    if(fp->buffer[fp->_SIZE-1] == '\n')
    {
      write(fp->fileon,fp->buffer,fp->_SIZE);
      fp->_SIZE = 0;
    }
  }
}

_FILE* _fopen(const char* pathName,const char* mode)
{
  int flag = 0;
  int defaultMode = 0666;
  if(strcmp(mode,"r") == 0)
  {
    flag |= O_RDONLY;
  }
  else if(strcmp(mode,"w") == 0)
  {
    flag |= O_WRONLY | O_TRUNC | O_CREAT;
  }
  else if(strcmp(mode,"a") == 0)
  {
    flag |= O_WRONLY | O_APPEND | O_CREAT;
  }
  int fd = 0;
  if(flag & O_RDONLY)
   fd = open(pathName,flag);
  else 
   fd = open(pathName,flag,defaultMode);

  if(fd<0)
  {
    //open failed
    const char* err = strerror(fd);
    write(2,err,strlen(err));
    return NULL;
  }
  _FILE* ret = (_FILE*)malloc(sizeof(_FILE));
  assert(ret);
  //init the struct
  ret->_flags = SYNC_LINE;
  ret->fileon = fd;
  ret->cap = NUM;
  ret->_SIZE = 0;
  memset(ret->buffer,0,NUM);
  return ret;
}
void _fflush(_FILE* fp)
{
  if(fp->_SIZE >0)
    write(fp->fileon,fp->buffer,fp->_SIZE);
}
void _fclose(_FILE* fp)
{
  _fflush(fp);
  close(fp->fileon);
}
